package com.itheima.demo.controller;

import com.itheima.demo.config.SecurityConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.sound.midi.Soundbank;

@RestController
public class HelloController {

    /**
     * 获取认证用户信息
     * @return
     */
    @GetMapping
    public Authentication getUserInfo(){
        //从security上下文中获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication;
    }

    /**
     * 要求登录用户必须具有‘p’权限可以访问资源
     * 没有指定访问规则：什么权限，角色，默认只要认真通过了 就可以访问
     * @return
     */
    @GetMapping("/hello")
    public String hello(){
        return "hello security!";
    }


    /**
     * 具有p1权限才能访问
     * @return
     */
    @GetMapping("/r/r1")
    public String r1(){
        return "r1";
    }


    /**
     * 具有p2权限才能访问
     * @return
     */
    @GetMapping("/r/r2")
    public String r2(){

        return "r2";
    }


    /**
     * 方法级别权限校验：基于动态代理技术实现
     * @return
     */
    @PreAuthorize("hasAnyAuthority('x', 'p1')")
    @GetMapping("/test")
    public String test(){
        return "test";
    }
}
